package tool

import (
	"cloud-disk/core/helper"
	"fmt"
	"math"
	"net/http"
	"os"
)

const chunkSize = 1024 * 1024 * 3

//FileChunk 文件分片
func FileChunk(r *http.Request) ([]string, error) {
	myFile, header, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}
	chunkNum := math.Ceil(float64(header.Size) / float64(chunkSize))
	b := make([]byte, chunkSize)

	var fileItem []string
	for i := 0; i < int(chunkNum); i++ {
		_, err := myFile.Seek(int64(i*chunkSize), 0) // 指定读取文件的信息点起始位置
		if err != nil {
			return nil, err
		}
		if chunkSize > header.Size-int64(i*chunkSize) {
			b = make([]byte, header.Size-int64(i*chunkSize))
		}
		_, err = myFile.Read(b)
		if err != nil {
			return nil, err
		}

		itemFilePath := fmt.Sprintf("./data/chunk_%s.chunk", helper.GetUUID())

		f, err := os.OpenFile(itemFilePath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
		if err != nil {
			return nil, err
		}
		fileItem = append(fileItem, itemFilePath)
		f.Write(b)
		f.Close()
	}
	myFile.Close()
	return fileItem, nil
}
